﻿using HuiZe.education.Model;
using HuiZe.education.Resource.Controls;
using HuiZe.education.ViewModel;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Reflection;
using Spire.Presentation;
using System.IO;
using HuiZe.education.Common;
using Label = System.Windows.Controls.Label;
using Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Word;

namespace HuiZe.education.View
{
    /// <summary>
    /// BeginClass23.xaml 的交互逻辑
    /// </summary>
    public partial class ShowResource2 : System.Windows.Window
    {
        public ShowResource2()
        {
            InitializeComponent();
            //var w = new WebBrowserOverlay(this.BdBrowser);
            //var wb = w.WebBrowser;
            //var HelpUrl = "file:\\I:\\wpf_jz111\\huize-edu\\HuiZeOutPut\\ConvertHtmls\\191d0de1296c1c3b1ca34c773c3582df.html";
            //wb.Navigate(new System.Uri(HelpUrl));
            Loaded += ResourceView_Loaded;


        }
        PlanLessonViewModel planLessoniewModel { get; set; }
        public string BkType { get; set; }
        public string BkId { get; set; }
        public ObservableCollection<ResourceCenterModel> resources { get; set; }

        private void ResourceView_Loaded(object sender, RoutedEventArgs e)
        {
            //webBrowser0 = new WebBrowser();
            //webBrowser0.ScriptErrorsSuppressed = true;
             planLessoniewModel = DataContext as PlanLessonViewModel;
            resCourseListChildModel obj0 = null;
            resBKCategoryCourseChildModel obj1 = null;
            ReqGroupFileListDetialModel obj2 = null;
            resBKCategoryCourseChildModel obj3 = null;
            if (BkType == "0")
            {
                obj0 = planLessoniewModel.GetResourceKcZy(BkId);
                resList.Children.Clear();

                PlayBookControl playBook = new PlayBookControl
                {

                    SourceUrl = obj0.file,
                    Imageurl = obj0.cover,
                    Imagetxt = obj0.resources_name,
                    Width = 371,
                    Height = 70,
                    Margin = new Thickness(5, 5, 0, 0),


                };
                //playBook.ImageButton.SourceUrl = item.file;
                playBook.PreviewMouseUp += customButton_Click;

                //CustomButton customButton = new CustomButton()
                //{
                //    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                //    ImageSource = new BitmapImage(new Uri(obj0.cover)),
                //    SourceUrl = obj0.file,
                //    //MeadiaType
                //    Content = obj0.resources_name,
                //    Width = 100,
                //    Height = 50,
                //    Margin = new Thickness(0, 0, 10, 0),
                //};
                //customButton.Click += customButton_Click;
                resList.Children.Add(playBook);
            }
            if (BkType == "1")
            {
                obj1 = planLessoniewModel.GetResourceCenter(BkId);

                resList.Children.Clear();


                PlayBookControl playBook = new PlayBookControl
                {

                    SourceUrl = obj1.file,
                    Imageurl = obj1.image,
                    Imagetxt = obj1.resources_name,
                    Width = 371,
                    Height = 70,
                    Margin = new Thickness(5, 5, 0, 0),


                };
                //playBook.ImageButton.SourceUrl = item.file;
                playBook.PreviewMouseUp += customButton_Click;
                //CustomButton customButton = new CustomButton()
                //{
                //    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                //    ImageSource = new BitmapImage(new Uri(obj1.image)),
                //    SourceUrl = obj1.file,
                //    //MeadiaType
                //    Content = obj1.resources_name,
                //    Width = 80,
                //    Height = 50,
                //    Margin = new Thickness(0, 0, 10, 0),
                //};
                //customButton.Click += customButton_Click;
                resList.Children.Add(playBook);



            }
            if (BkType == "2")
            {
                obj2 = planLessoniewModel.GetResourceMySpace(BkId);
                if(obj2!=null)
                { 
                resList.Children.Clear();
                PlayBookControl playBook = new PlayBookControl
                {

                    SourceUrl = obj2.file,
                    Imageurl = obj2.file,
                    Imagetxt = obj2.file_name,
                    Width = 371,
                    Height = 70,
                    Margin = new Thickness(5, 5, 0, 0),


                };
                //playBook.ImageButton.SourceUrl = item.file;
                playBook.PreviewMouseUp += customButton_Click;

                //CustomButton customButton = new CustomButton()
                //{
                //    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                //    ImageSource = new BitmapImage(new Uri(obj2.file)),
                //    SourceUrl = obj2.file,
                //    //MeadiaType
                //    Content = obj2.file_name,
                //    Width = 100,
                //    Height = 50,
                //    Margin = new Thickness(0, 0, 10, 0),
                //};
                //customButton.Click += customButton_Click;


                resList.Children.Add(playBook);
                }
            }

            if (BkType == "3")
            {
                obj3 = planLessoniewModel.GetMyCllection(BkId);

                resList.Children.Clear();
                PlayBookControl playBook = new PlayBookControl
                {

                    SourceUrl = obj3.file,
                    Imageurl = obj3.image,
                    Imagetxt = obj3.resources_name,
                    Width = 371,
                    Height = 70,
                    Margin = new Thickness(5, 5, 0, 0),


                };
                //playBook.ImageButton.SourceUrl = item.file;
                playBook.PreviewMouseUp += customButton_Click;
                //CustomButton customButton = new CustomButton()
                //{
                //    Template = (ControlTemplate)FindResource("HZImageButtonTemplate"),
                //    ImageSource = new BitmapImage(new Uri(obj3.image)),
                //    SourceUrl = obj3.file,
                //    //MeadiaType
                //    //Content = obj3.ziyuan.resources_name,
                //    Width = 100,
                //    Height = 50,
                //    Margin = new Thickness(0, 0, 10, 0),
                //};
                //customButton.Click += customButton_Click;


                resList.Children.Add(playBook);
            }




        }
        public static bool officeFileOpen_Status = false;
        System.Windows.Xps.Packaging.XpsDocument xpsDoc;
        private void customButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            PlayBookControl customButton = sender as PlayBookControl;
            //string preUrl = "https://ow365.cn/?i=28004&ssl=1&n=5&furl=";
            string url = customButton.SourceUrl;
            //MediaPlayBorder.Children.Clear();


            if (url.ToString().Contains("jpg") || url.ToString().Contains("png"))
            {

                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();
                //webBrowser11.Navigate("file:\\" + LocalPath);
            }
            else if (url.ToString().Contains("mp3") || url.ToString().Contains("mp4") || url.ToString().Contains("wav")||url.ToString().Contains("swf") )
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();



            }
            else if (url.ToString().Contains("ppts") || url.ToString().Contains("ppt"))
            {
                videoPgae.Visibility = Visibility.Collapsed;
                otherPgae.Visibility = Visibility.Visible;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\"); ;
                //pageContent.Content = f1;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                OpenSourceFile(LocalPath);


            }
            else if (  url.ToString().Contains("flash"))
            {
                //string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                //PdfPgae.Visibility = Visibility.Visible;
                //videoPgae.Visibility = Visibility.Collapsed;
                //otherPgae.Visibility = Visibility.Collapsed;
                //moonPdfPanel.OpenFile(LocalPath);

                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");

                //pageContent.Content = f2;
                videoPgae.Visibility = Visibility.Visible;
                otherPgae.Visibility = Visibility.Collapsed;
                mediaElement.Source = new Uri(LocalPath);
                mediaElement.Play();


            }
            else if (url.ToString().Contains("doc") || url.ToString().Contains("docx"))
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                videoPgae.Visibility = Visibility.Collapsed;
                otherPgae.Visibility = Visibility.Visible;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                OpenSourceFile(LocalPath);


            }
            else if (url.ToString().Contains("xlsx") || url.ToString().Contains("xls"))
            {
                string LocalPath = DownLoadFile(url, AppDomain.CurrentDomain.BaseDirectory + "\\ConvertHtmls\\");
                videoPgae.Visibility = Visibility.Collapsed;
                otherPgae.Visibility = Visibility.Visible;
                documentViewer1.Height = otherPgae.Height;
                documentViewer1.Width = otherPgae.Width;
                OpenSourceFile(LocalPath);

            }
            else
            {



            }


        }
        private void OpenSourceFile(string FilePath)
        {

            string xpsFilePath = string.Empty;

            var convertResults = OfficeToXps.ConvertToXps(FilePath, ref xpsFilePath);
            switch (convertResults.Result)
            {
                case ConversionResult.OK:
                    xpsDoc = new System.Windows.Xps.Packaging.XpsDocument(xpsFilePath, FileAccess.Read);
                    documentViewer1.Document = xpsDoc.GetFixedDocumentSequence();
                    officeFileOpen_Status = true;
                    break;

                case ConversionResult.InvalidFilePath:
                    // Handle bad file path or file missing
                    break;
                case ConversionResult.UnexpectedError:
                    // This should only happen if the code is modified poorly
                    break;
                case ConversionResult.ErrorUnableToInitializeOfficeApp:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToOpenOfficeFile:
                    // Handle source file being locked or invalid permissions
                    break;
                case ConversionResult.ErrorUnableToAccessOfficeInterop:
                    // Handle Office 2007 (Word | Excel | PowerPoint) not installed
                    break;
                case ConversionResult.ErrorUnableToExportToXps:
                    // Handle Microsoft Save As PDF or XPS Add-In missing for 2007
                    break;
            }
        }
        private string DownLoadFile(string url, string savepath)
        {
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string downloadpath = savepath + "\\" + FileName + extention;
            WebApiHelper.Download(url, downloadpath);

            return downloadpath;


        }

        private void close_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.Close();
        }



        private void SourceTree_PreviewMouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {


        }









        /// 预览Excel
        /// </summary>
        /// <param name="physicalPath">解码的地址</param>
        /// <param name="url"></param>
        public string PreviewExcel(string url, string savepath)
        {
            var resultUrl = string.Empty;
            var serverUrl = string.Empty;

            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);



                Microsoft.Office.Interop.Excel.Application application = null;
                //参数
                Workbook workbook = null;
                application = new Microsoft.Office.Interop.Excel.Application();
                object missing = Type.Missing;
                object trueObject = true;
                application.Visible = false;
                application.DisplayAlerts = false;
                workbook = application.Workbooks.Open(downloadpath, missing, trueObject, missing, missing, missing,
                   missing, missing, missing, missing, missing, missing, missing, missing, missing);
                object format = XlFileFormat.xlHtml;
                string htmlName = Path.GetFileNameWithoutExtension(downloadpath) + ".html";
                String outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
                workbook.SaveAs(outputFile, XlFileFormat.xlHtml, null, null, false, false,
                   XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);

                workbook.Close();
                application.Quit();
                resultUrl = Path.GetDirectoryName(url) + "\\" + htmlName;
                var lastUrl = Path.GetFileName(resultUrl);
                //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
                //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];

                return outputFile;
            }
            catch (Exception ex)
            {
                //this.Write(ex);
            }
            return serverUrl + resultUrl;
        }
        /// 预览Word（HtmL类型）
        /// </summary>
        /// <param name="physicalPath"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public string PreviewWord(string url, string savepath)
        {

            var resultUrl = string.Empty;
            var serverUrl = string.Empty;
            object outputFile1 = new object();
            object missing1 = new object();

            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);


            //检查doc 是否被实例化
            var idd = 0;
            var ss = 1;
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);



                Microsoft.Office.Interop.Word._Application application = null;
                Microsoft.Office.Interop.Word._Document doc = null;
                application = new Microsoft.Office.Interop.Word.Application();
                //参数
                object missing = Missing.Value;
                object trueObject = true;
                application.Visible = false;
                application.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                object physicalPathObj = downloadpath;
                //实例化
                doc = application.Documents.Open(ref physicalPathObj, ref missing, ref trueObject, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
                string htmlName = Path.GetFileNameWithoutExtension(url) + ".html";
                object outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
                object format = WdSaveFormat.wdFormatHTML;
                outputFile1 = outputFile;
                missing1 = missing;
                idd = doc.DocID;
                ss = doc.CompatibilityMode;
                //转换并保存
                doc.SaveAs(ref outputFile, ref format, ref missing, ref missing, ref missing,
                                      ref missing, XlSaveAsAccessMode.xlNoChange, ref missing,
                                      ref missing, ref missing, ref missing, ref missing);
                doc.Close();
                application.Quit();
                //返回137的路径                  
                resultUrl = Path.GetDirectoryName(url) + "\\" + htmlName;
                var lastUrl = Path.GetFileName(resultUrl);

                return outputFile.ToString();
                //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
                //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
            }
            catch (Exception ex)
            {
                //this.Write(ex, $"{outputFile1}+{missing1}+{idd.ToString()}+{ss.ToString()}+{physicalPath}");

            }
            return serverUrl + resultUrl;
        }
        #region  预览ppt（使用Presentation插件）
        /// <summary>
        /// ppt转html
        /// </summary>
        /// <returns></returns>
        public string PptToHtml(string url, string savepath)
        {
            var resultUrl = string.Empty;
            var serverUrl = string.Empty;
            string extention = Path.GetExtension(url);
            string FileName = Path.GetFileNameWithoutExtension(url);
            string htmlName = Path.GetFileNameWithoutExtension(url) + ".html";
            String outputFile = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            //实例化Presentation类，加载文件
            Spire.Presentation.Presentation ppt = new Spire.Presentation.Presentation();
            try
            {
                string downloadpath = savepath + "\\" + FileName + extention;
                WebApiHelper.Download(url, downloadpath);

                ppt.LoadFromFile(downloadpath);
                ppt.SaveToFile(outputFile, FileFormat.Html);

                //打开文件

                //保存文件为HTML

            }//`在这里插入代码片`
            catch (Exception ex)
            {
                //this.Write(ex);
            }
            //得到返回的html地址
            resultUrl = Path.GetDirectoryName(savepath) + "\\" + htmlName;
            var lastUrl = Path.GetFileName(resultUrl);
            //resultUrl = ConfigurationManager.AppSettings["ResultUrl"] + lastUrl;
            //serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
            return outputFile;


        }






        #endregion

        private void exitAddStu_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
